<template>
    <div id='myApp'>
        <Row style="margin-bottom: 10px;border-bottom: 1px solid #eeeeee;">
            <Col span="7" style="border-bottom:2px solid #2d8cf0 ;padding: 0 0 8px 18px;">
            <span style="color: #2d8cf0;">
                <Icon type="md-add-circle" />&nbsp;&nbsp;
                <span style="color: black;">接口管理&nbsp;&nbsp;>&nbsp;&nbsp;关键管理&nbsp;&nbsp;>&nbsp;&nbsp;</span>创建KEY
            </span>
            </Col>
        </Row>
        <Row class="creatkeyform">
            <Col span="12" offset="4">
            <Form ref="ruleForm" :rules="ruleValidate" :model="ruleForm" :label-width="180">
                <FormItem prop="apiName" label="API名称：">
                    <Input v-model="ruleForm.apiName" />
                </FormItem>
                <FormItem prop="userName" label="接入者名称：">
                    <Input v-model="ruleForm.userName" />
                </FormItem>
                <FormItem prop="userIP" label="接入者IP：">
                    <Input v-model="ruleForm.userIP" />
                </FormItem>
                <FormItem prop="key" label="API KEY：">
                    <Input v-model="ruleForm.key" :search="true" enter-button="生成KEY" @on-search="createCodeKey(1)"/>
                </FormItem>
                <FormItem prop="checkCode" label="校验码：">
                    <Input v-model="ruleForm.checkCode" :search="true" enter-button="生成校验码" @on-search="createCodeKey(2)" />
                </FormItem>
                <FormItem prop="enabled" label="状态：">
                    <i-switch v-model="ruleForm.enabled" size="large" @on-change="changestatus">
                        <span slot="open">启用</span>
                        <span slot="close">停用</span>
                    </i-switch>
                </FormItem>
                <FormItem>
                    <Button type="primary" style="width: 100px;" @click="saveKey">保存</Button>
                </FormItem>
            </Form>
            </Col>
        </Row>


    </div>
</template>
<style type="text/css">
.creatkeyform .ivu-input-group-append,.creatkeyform .ivu-input-group-prepend{
    width: 110px;
}
</style>
<style scoped>
</style>
<script>
    import { mapState, mapActions } from 'vuex'
    import zmitiUtil from '../../lib/util'
    export default {
        computed: mapState({
            Authorization: state => state.Authorization
        }),
        data() {
            const validateApiname = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入API名称'));
                }
                // 异步验证
                setTimeout(() => {
                    var path='apikey/list';
                    var postData = {
                        enabled:true,
                        apiName:value
                    };
                    zmitiUtil.Ajax(path,postData).then(res => {
                        var data = res.data;
                        
                        if(res.data.total>0){
                            value=res.data.results[0].apiName;
                            callback(new Error('API名称已存在'));
                        }else{                            
                            callback();
                        }
                        
                    }).catch((error) => {
                        console.log(error,'error');
                    });

                }, 1000);
            };
            return {
                isEdit: '',
                ruleForm: {
                    apiName:'',
                    userName:'',
                    userIP:'',
                    key:'',
                    checkCode:'',
                    enabled:true
                },
                ruleValidate: {
                    apiName: [
                        { validator: validateApiname,required: true, trigger: 'blur' }
                    ],
                    key: [
                        { required: true, message: '请输入API KEY', trigger: 'blur' }
                    ],
                    checkCode: [
                        { required: true, message: '请输入校验码', trigger: 'blur' }
                    ]
                }
            }
        },
        mounted() {
            
        },
        methods: {
            changestatus(status){//是否启用
                this.ruleForm.enabled=status;                
                console.log(status,'status');
            },
            saveKey(){
                var _this = this;                
                var path='apikey/create';
                var postData = _this.ruleForm
                console.log(postData,'postData');
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        zmitiUtil.Ajax(path,postData).then(res => {
                            var data = res.data;               
                            if (data.code==1) {
                                _this.$Message.success('添加成功!');
                                _this.$router.push('/keyManage')
                            }else{
                                console.log(res.data,'错误');
                                _this.$Message.error(data.result);
                            }
                        }).catch((error) => {
                            console.log(error,'error');
                        });
                    } else {
                        this.$Message.error('请填写完整!');
                    }
                })
            },
            createCodeKey(type){//生成code
                 /*type=1:key，type=2：checkCode*/
                var _this = this;                
                var path='apikey/generateKey';
                var postData ={
                    length:type==1?32:16
                }
                zmitiUtil.Ajax(path,postData).then(res => {
                    var data = res.data;
                    if(res.data.key){                       
                        if(type==1){
                            _this.ruleForm.key=res.data.key;
                        }else{
                            _this.ruleForm.checkCode=res.data.key;
                        }                        
                    }                    
                }).catch((error) => {
                    console.log(error,'error');
                });
            }
        }
    }
</script>